<script setup>
import { computed, ref, watch } from "vue";
import { projectDetail, allotUser } from "@/api/project";
import { useStore } from "vuex";
import { toast } from "@/hook/toast";
import { useConcurrence } from "@/hook/concurrence";
import { delay } from "@/utils";

const store = useStore()
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
  }
})
const emits = defineEmits(['update:modelValue', 'addSuccess'])
const visible = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emits('update:modelValue', value)
  }
})
async function initData(xiangmu_id) {
  projectId.value = xiangmu_id
  return
  const resp = await projectDetail({ xiangmu_id })
  const { code, data, msg } = resp
  if (code !== 1) return toast({ title: msg })
  const { user_job_info } = data
  if (!user_job_info || !user_job_info.length) return
  const options = {
    '1': {
      valueKey: 'qianduan',
      dateKey: 'qianduan_date',
    },
    '2': {
      valueKey: 'houduan',
      dateKey: 'houduan_date',
    },
    '3': {
      valueKey: 'ui',
      dateKey: 'ui_date',
    }
  };
  user_job_info.forEach(item => {
    const { user_id, start_date, end_date, shenfen } = item
    const targetOpt = options[shenfen]
    if (!targetOpt) return
    const { valueKey, dateKey } = targetOpt
    formData.value[valueKey] = user_id
    formData.value[dateKey] = [start_date, end_date]
    const disabledKey = `${valueKey}_disabled`
    formData.value[disabledKey] = true
  })
}

defineExpose({
  initData,
})


const userOptions = computed(() => store.getters.userList.map(item => {
  const { id, nickname } = item
  return { value: id, label: nickname }
}))

function resetForm() {
  formData.value = {
    qianduan: '',
    qianduan_date: [],
    qianduan_disabled: false,
    houduan: '',
    houduan_date: [],
    houduan_disabled: false,
    ui: '',
    ui_date: '',
    ui_disabled: false,
  }
}

const projectId = ref('')
watch(() => visible.value, value => {
  if (!value) return
  store.dispatch('users/initUserList')
})
const formData = ref({
  qianduan: '',
  qianduan_date: [],
  qianduan_disabled: false,
  houduan: '',
  houduan_date: [],
  houduan_disabled: false,
  ui: '',
  ui_date: '',
  ui_disabled: false,
})

const loading = ref(false)

async function fetchJobUser() {
  console.log('执行两')
  const options = getRequestOptions(projectId.value)
  if (!options.length) return toast({ title: '请完善表单' })
  loading.value = true
  function request(...payload) {
    return new Promise(resolve => {
      allotUser(...payload).then(resp => {
        resolve([null, resp])
      }).catch(err => {
        resolve([err, null])
      })
    })
  }
  console.log('执行到这3', options, request)
  const resp = await useConcurrence(options, 3, request)
  console.log('执行到这4', resp)
  const isSuccess = resp.every(([error]) => !error)
  console.log('执行到这5', isSuccess)
  await delay(300)
  loading.value = false
  if (!isSuccess) return
  console.log('指令6')
  toast({ title: '分配成功' })
  visible.value = false
  emits('addSuccess')
}

function getRequestOptions(proId) {
  const keys = ['qianduan', 'houduan', 'ui']
  const typeEnum = {
    qianduan: 1,
    houduan: 2,
    ui: 3,
  }
  return keys.filter(key => {
    const value = formData.value[key].toString()
    // const disabledKey = `${key}_disabled`
    //&& !formData.value[disabledKey]
    return !!(value.length)
  }).map(key => {
    const dateKey = `${key}_date`
    const dateValue = formData.value[dateKey]
    const [startDate, endDate] = dateValue
    const userId = formData.value[key]
    return {
      payload: [
        {
          start_date: startDate,
          end_date: endDate,
          job_user_id: userId,
          shenfen: typeEnum[key],
          xiangmu_id: proId,
        }
      ]
    }
  })
}

const btnDisabled = computed(() => {
  const keys = ['qianduan', 'houduan', 'ui']
  const value = keys.map(key => {
    return formData.value[`${key}_disabled`]
  })
  return value.every(item => item)
})

function cancelHandle() {
  visible.value = false
}

function confirmHandle() {
  fetchJobUser()
}
</script>

<template>
  <el-drawer v-model="visible" title="分配人员" :size="660" @closed="resetForm">
    <el-form ref="formRef" :model="formData" label-position="left" label-width="70px">
      <el-form-item label="前端">
        <el-select placeholder="请选择前端人员" v-model="formData.qianduan" clearable default-first-option filterable>
          <el-option v-for="(item, index) in userOptions" :key="index" :value="item.value" :label="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item label="前端工期">
        <el-date-picker v-model="formData.qianduan_date" type="daterange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" value-format="YYYY-MM-DD" unlink-panels :teleported="false" />
      </el-form-item>
      <el-form-item label="后端">
        <el-select placeholder="请选择后端人员" v-model="formData.houduan" clearable default-first-option filterable>
          <el-option v-for="(item, index) in userOptions" :key="index" :value="item.value" :label="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item label="后端工期">
        <el-date-picker v-model="formData.houduan_date" type="daterange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" value-format="YYYY-MM-DD" unlink-panels :teleported="false" />
      </el-form-item>
      <el-form-item label="UI">
        <el-select placeholder="请选择UI人员" v-model="formData.ui" clearable default-first-option filterable>
          <el-option v-for="(item, index) in userOptions" :key="index" :value="item.value" :label="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item label="UI工期">
        <el-date-picker v-model="formData.ui_date" type="daterange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" value-format="YYYY-MM-DD" unlink-panels :teleported="false" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-space>
        <el-button type="info" plain @click="cancelHandle">取消操作</el-button>
        <el-button :loading="loading" :disabled="btnDisabled" type="primary" @click="confirmHandle">提交保存
        </el-button>
      </el-space>
    </template>
  </el-drawer>
</template>

<style scoped lang="scss"></style>

